package com.open.center.jwt.config;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.interfaces.RSAPublicKey;
import java.util.Base64;
import java.util.Enumeration;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

/**
 * Jwt全局配置
 *
 * @author Riche's
 * @since 2025/5/23
 */
@Slf4j
@Data
@Configuration
public class JwtConfig {

    private final JwtProperties jwtProperties;

    private RSAPublicKey publicKey;

    private PrivateKey privateKey;

    public JwtConfig(JwtProperties jwtProperties) throws KeyStoreException, IOException,
            CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException {
        this.jwtProperties = jwtProperties;
        byte[] decode = Base64.getDecoder().decode(jwtProperties.getStorePass());
        String password = new String(decode, StandardCharsets.UTF_8);
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        ClassPathResource pathResource = new ClassPathResource(jwtProperties.getKeyStore());
        keyStore.load(pathResource.getInputStream(), password.toCharArray());
        Enumeration<String> aliases = keyStore.aliases();
        String alias = null;
        if (aliases.hasMoreElements()) {
            alias = aliases.nextElement();
        }
        publicKey = (RSAPublicKey) keyStore.getCertificate(alias).getPublicKey();
        privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray());
        log.info("-----初始化PKCS12密钥库：公钥、私钥-----");
    }

}
